package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.UserHolder;
import io.reactivex.Completable;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 优惠券，异步处理订单
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder>
    implements IVoucherOrderService {

    @Resource
    private ISeckillVoucherService seckillVoucherService;

    @Resource
    private RedisIdWorker redisIdWorker;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private RedissonClient redissonClient;

    private IVoucherOrderService proxy;

    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;

    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }

    /**
     * 线程池
     */
    private static final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();

    /**
     * 类初始化完成后执行，初始化匿名内部类
     */
    @PostConstruct
    private void init() {
        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
    }

    private class VoucherOrderHandler implements Runnable {
        String queueName = "stream.orders";

        @Override
        public void run() {
            while (true) {
                try {
                    // 获取消息队列中的订单信息 xreadgroup group g1 c1 count 1 block 2000 streams streams.order >
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                        Consumer.from("g1", "c1"), StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                        StreamOffset.create(queueName, ReadOffset.lastConsumed()));
                    // 判断消息是否获取成功
                    if (list == null || list.isEmpty()) {
                        // 如果获取失败，说明没有消息，继续下次循环
                        continue;
                    }
                    orderHandle(list);
                } catch (Exception e) {
                    log.error("处理订单异常 : {}", e.toString());
                    handlePendingList();
                }
            }
        }

        private void orderHandle(List<MapRecord<String, Object, Object>> list) {
            // 解析消息中的订单信息
            MapRecord<String, Object, Object> record = list.get(0);
            Map<Object, Object> values = record.getValue();
            // 将map转换为对象并忽略错误
            VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(values, new VoucherOrder(), true);
            // 如果获取成功，下单
            handleVoucherOrder(voucherOrder);
            // ACK确认 sack stream.orders g1 id
            stringRedisTemplate.opsForStream().acknowledge(queueName, "g1", record.getId());
        }

        private void handlePendingList() {
            while (true) {
                try {
                    // 获取pending-list中的订单信息 xreadgroup group g1 c1 count 1 block 2000 streams streams.order >
                    List<MapRecord<String, Object, Object>> list =
                        stringRedisTemplate.opsForStream().read(Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1), StreamOffset.create(queueName, ReadOffset.from("0")));
                    // 判断消息是否获取成功
                    if (list == null || list.isEmpty()) {
                        // 如果获取失败，说明pending-list没有异常消息，结束循环
                        break;
                    }
                    // 解析消息中的订单信息
                    orderHandle(list);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 秒杀券抢购
     *
     * @param voucherId 优惠券id
     * @return 抢购结果
     * @author walls1717
     */
    @Override
    public Result seckillVoucher(Long voucherId) {
        // 执行lua脚本
        long orderId = redisIdWorker.nextId("order");
        Long userId = UserHolder.getUser().getId();
        Long result = stringRedisTemplate.execute(SECKILL_SCRIPT, Collections.emptyList(), voucherId.toString(),
            userId.toString(), String.valueOf(orderId));
        assert result != null;
        if (result != 0) {
            return Result.fail(result == 1 ? "库存不足！" : "不能重复下单！");
        }
        // 获取代理对象（事务）
        proxy = (IVoucherOrderService)AopContext.currentProxy();
        return Result.ok(orderId);
    }

    /**
     * 创建优惠券订单
     *
     * @param voucherId 优惠券id
     * @param seckillVoucher 秒杀券
     * @return 结果
     * @author walls1717
     */
    @Override
    @Transactional
    public Result createVoucherOrder(Long voucherId, SeckillVoucher seckillVoucher) {
        // 一人一单
        Long userId = UserHolder.getUser().getId();

        Integer count =
            this.lambdaQuery().eq(VoucherOrder::getVoucherId, voucherId).eq(VoucherOrder::getUserId, userId).count();
        if (count > 0) {
            return Result.fail("您已经购买过此优惠券了！");
        }

        // 判断库存是否充足
        Integer stock = seckillVoucher.getStock();
        if (stock < 1) {
            return Result.fail("库存不足！");
        }
        // 库存充足扣减库存
        boolean stockFlag = seckillVoucherService.lambdaUpdate().setSql("stock = stock - 1")
            .eq(SeckillVoucher::getVoucherId, voucherId).gt(SeckillVoucher::getStock, 0).update();
        if (!stockFlag) {
            return Result.fail("库存不足！");
        }

        // 保存订单
        VoucherOrder voucherOrder = new VoucherOrder();
        long orderId = redisIdWorker.nextId("order");
        voucherOrder.setId(orderId);
        voucherOrder.setVoucherId(voucherId);
        voucherOrder.setUserId(userId);
        this.save(voucherOrder);

        return Result.ok(orderId);
    }

    @Override
    @Transactional
    public void createVoucherOrder2(VoucherOrder voucherOrder) {
        // 一人一单
        Long userId = voucherOrder.getUserId();
        Integer count = this.lambdaQuery().eq(VoucherOrder::getVoucherId, voucherOrder.getVoucherId())
            .eq(VoucherOrder::getUserId, userId).count();
        if (count > 0) {
            log.error("用户已经购买过一次");
            return;
        }

        // 库存充足扣减库存
        boolean stockFlag = seckillVoucherService.lambdaUpdate().setSql("stock = stock - 1")
            .eq(SeckillVoucher::getVoucherId, voucherOrder.getVoucherId()).gt(SeckillVoucher::getStock, 0).update();
        if (!stockFlag) {
            log.error("库存不足");
        }

        // 保存订单
        this.save(voucherOrder);
    }

    /**
     * 处理订单
     *
     * @param voucherOrder 订单
     */
    private void handleVoucherOrder(VoucherOrder voucherOrder) {
        Long userId = voucherOrder.getUserId();
        RLock lock = redissonClient.getLock("lock:order:" + userId);
        boolean isLock = lock.tryLock();
        // 判断是否获取锁
        if (!isLock) {
            // 获取锁失败
            log.error("不允许重复下单");
            return;
        }

        try {
            proxy.createVoucherOrder2(voucherOrder);
        } finally {
            // 释放锁
            lock.unlock();
        }
    }
}
